
package com.polarrose.spring.bayeux.jetty;

import dojox.cometd.Bayeux;
import org.mortbay.cometd.continuation.ContinuationCometdServlet;

import javax.servlet.ServletException;
import java.util.HashMap;
import java.util.Map;

/**
 * Subclass of Jetty's {@link org.mortbay.cometd.continuation.ContinuationCometdServlet} that keeps track of
 * {@link dojox.cometd.Bayeux} instances and provides a way to look those up by (servlet) name.
 *
 * @author Stefan Arentz
 */

public class JettyBayeuxServlet extends ContinuationCometdServlet
{
    /**
     * Bayeux instances mapped by servlet name.
     */

    private static final Map<String, Bayeux> bayeuxs = new HashMap<String, Bayeux>();

    /**
     * @see org.mortbay.cometd.continuation.ContinuationCometdServlet#init()
     */

    public void init() throws ServletException
    {
        super.init();

        synchronized(bayeuxs) {
            bayeuxs.put(
                getServletName(),
                (Bayeux) getServletContext().getAttribute(Bayeux.DOJOX_COMETD_BAYEUX)
            );
        }
    }

    /**
     * Return the default {@link dojox.cometd.Bayeux} instance.
     *
     * @return the default {@link dojox.cometd.Bayeux} instance
     */

    static Bayeux getDefaultBayeux()
    {
        if (bayeuxs.size() == 0) {
            throw new RuntimeException("No JettyBayeuxServlet has been configured");
        }

        if (bayeuxs.size() != 1) {
            throw new RuntimeException("Multiple JettyBayeuxServlet instances configured");
        }

        return bayeuxs.values().iterator().next();
    }

    /**
     *
     * @param name the name of the {@link com.polarrose.spring.bayeux.jetty.JettyBayeuxServlet}
     * @return the {@link dojox.cometd.Bayeux} instance
     */

    static Bayeux getBayeuxByServletName(String name)
    {
        return bayeuxs.get(name);
    }
}
